#include "stdinc.h"
#include "DCPlusPlus.h"

#include "SyntaxManager.h"
#include "SimpleXML.h"

void SyntaxManager::loadKeywords() {
	try {
		SimpleXML xml;
		xml.fromXML(File(Util::getAppPath() + "XML\\Keywords.xml", File::READ, File::OPEN).read());
		
		if(xml.findChild("Keywords")) {
			xml.stepIn();
			loadKeywords(&xml);
			xml.stepOut();
		}
	} catch(const Exception& e) {
		dcdebug("SyntaxManager::loadKeywords: %s\n", e.getError().c_str());
	}
}

void SyntaxManager::loadKeywords(SimpleXML* aXml) {
	aXml->resetCurrentChild();
	while(aXml->findChild("Keyword")) {
		keywords.push_back(
			Keywords(
			aXml->getChildAttrib("Word"),
			aXml->getIntChildAttrib("Type")
			)
		);
	}
}

void SyntaxManager::saveKeywords() {
	try {
		SimpleXML xml;
		
		xml.addTag("Keywords");
		xml.stepIn();
		for(Keywords::Iter l = keywords.begin(); l != keywords.end(); ++l) {
			xml.addTag("Keyword");
			xml.addChildAttrib("Word", l->getKeyword());
			xml.addChildAttrib("Type", Util::toString(l->getType()));
		}
		xml.stepOut();

		string fname = Util::getAppPath() + "XML\\Keywords.xml";

		File f(fname + ".tmp", File::WRITE, File::CREATE | File::TRUNCATE);
		f.write(SimpleXML::w1252Header);
		f.write(xml.toXML());
		f.close();
		File::deleteFile(fname);
		File::renameFile(fname + ".tmp", fname);

	} catch(const Exception& e) {
		dcdebug("SyntaxManager::saveKeywords: %s\n", e.getError().c_str());
	}
}